搜索 K
Appearance
博客正在加载中...
Appearance
一个 Java 程序在启动的时候,总是需要读取配置文件。
为了表明配置文件在哪里,我们需要给定路径,例如:
String conf = "C:\\conf\\default.properties";如果在 C:\conf 目录下没有这个文件,就会报错,因为这是固定在代码里的;如果将配置文件挪个地方,甚至换到 Linux 系统下,又要改动代码并重新编译。
因此,从磁盘的固定目录读取配置文件,不是一个好的办法。那么应该怎么做呢?
我们可以将配置文件放到编译后的.class 文件所在的目录里(或者放到 jar 包),并且在 classpath 里指定配置文件的路径,从而避免不同环境下文件路径不一致的问题
在 classpath 中的资源文件,路径总是以 / 开头,我们先获取当前的 Class 对象,然后调用 getResourceAsStream() 就可以直接从 classpath 读取任意的资源文件。
我们新建一个 conf 目录,里面创建一个 default.properties 文件:
last_open_file=/fuk然后编写代码读取:
import java.io.InputStream;
import java.util.Properties;
public class IODemo9ClassPath {
public static void main(String[] args) {
try (InputStream input = IODemo9ClassPath.class.getResourceAsStream("/default.properties")) {
Properties props = new Properties();
props.load(input);
String last_open_file = props.getProperty("last_open_file");
System.out.println("last_open_file: " + last_open_file);
} catch (Exception e) {
e.printStackTrace();
}
}
}注意:如果资源文件不存在,它将返回 null。因此代码里应增加判空的语句
最后编译和运行:
$ javac -d conf IODemo9ClassPath.java
$ cd conf
$ java IODemo9ClassPath
last_open_file: /fuk